<template>
  <div>
    <van-card
        v-for="blog in props.blogList || []"
        :key="blog.id"
        :desc="blog.content"
        :title="blog.title"
        class="blog-card"
        :thumb="processImageUrl(blog.coverImage)"
        @click="toBlog(blog.id)">
      <template #tags>
        <van-tag
            plain
            color="#ffe1e1"
            text-color="#ad0000"
            style="margin-right: 8px; margin-top: 4px;"
            v-for="(tag, index) in getBlogTags(blog)"
            :key="index">
          {{ tag }}
        </van-tag>
      </template>
      <template #footer>
        <div class="blog-stats">
          <van-icon name="eye-o" /> {{ blog.viewNum || 0 }}
          <van-icon name="like-o" style="margin-left: 12px;" /> {{ blog.likeNum || 0 }}
          <van-icon name="star-o" style="margin-left: 12px;" /> {{ blog.starNum || 0 }}
          <van-icon name="chat-o" style="margin-left: 12px;" /> {{ blog.commentNum || 0 }}
        </div>
      </template>
    </van-card>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { BlogType } from "../models/blog";
import { processImageUrl } from '../utils/imageUtils';

const router = useRouter();

interface BlogIndexCardListProps {
  blogList: BlogType[];
}

const props = defineProps<BlogIndexCardListProps>();

const toBlog = (id: number) => {
  router.push({
    path: `/blog/detail/${id}`
  });
};

// 安全获取博客标签
const getBlogTags = (blog: BlogType) => {
  if (!blog || !blog.tags) {
    return [];
  }
  
  // 如果标签已经是数组，直接返回
  if (Array.isArray(blog.tags)) {
    return blog.tags;
  }
  
  // 尝试解析JSON字符串
  try {
    return typeof blog.tags === 'string' ? JSON.parse(blog.tags) : [];
  } catch (e) {
    console.error('解析博客标签出错:', e);
    return [];
  }
};
</script>

<style scoped>
.blog-card {
  margin-bottom: 8px;
  border-radius: 8px;
  background-color: #fff;
}

.blog-stats {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 12px;
}
</style>
